package server

import (
	"context"
	"errors"
	"longmen/server/config/global"
	"longmen/server/internal/api"
	"longmen/server/pkg/common/api_models"
	"longmen/server/pkg/common/helper/const"
	utils2 "longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"time"

	"gorm.io/gorm"
)

func (*Server) LiveAnchorPlanCreate(ctx context.Context, req *pb.AnchorLivePlanCreate) (*pb.AnchorLivePlan, error) {
	var err error
	if req.MatchId != 0 {
		match := &models_sports.MatchesSchedule{}
		err = global.Sport().Model(&models_sports.MatchesSchedule{}).Where("match_id=?", req.MatchId).First(&match).Error
		if err != nil {
			return nil, err
		}

		var matchID int
		err = global.Live().Model(&models_main.AnchorLivePlan{}).Where("match_id=?", match.MatchId).Pluck("match_id", &matchID).Error
		if err != nil {
			return nil, err
		}

		if matchID > 0 {
			return nil, errors.New("您已创建过该场赛事")
		}
	}

	r := &models_main.AnchorLivePlan{
		AnchorID:        req.AnchorId,
		MatchID:         req.MatchId,
		PlanTime:        req.PlanTime,
		Title:           req.Title,
		Ticket:          int(req.Ticket),
		CategoryID:      int(req.CategoryId),
		ChildCategoryID: int(req.ChildCategoryId),
		Thumb:           req.Thumb,
		CreatedAt:       time.Now().Unix(),
	}
	err = global.Live().Model(&models_main.AnchorLivePlan{}).Create(&r).Error
	if err != nil {
		return &pb.AnchorLivePlan{}, err
	}
	return &pb.AnchorLivePlan{
		Id:              r.ID,
		AnchorId:        r.AnchorID,
		MatchId:         r.MatchID,
		PlanTime:        r.PlanTime,
		Title:           r.Title,
		Ticket:          int32(r.Ticket),
		CategoryId:      req.CategoryId,
		ChildCategoryId: req.ChildCategoryId,
		Thumb:           req.Thumb,
		CreatedAt:       r.CreatedAt,
	}, nil
}

func (*Server) LiveAnchorPlan(ctx context.Context, req *pb.AnchorLivePlanReq) (*pb.AnchorLivePlanResp, error) {
	ret := &pb.AnchorLivePlanResp{}
	size, offset := utils2.Pagiation(int(req.Page), int(req.Size))
	err := global.Live().Model(&models_main.AnchorLivePlan{}).Where("anchor_id=?", req.Id).Order("plan_time desc").Count(&ret.Total).Offset(offset).Limit(size).Scan(&ret.LivePlan).Error
	if err != nil {
		return &pb.AnchorLivePlanResp{}, err
	}

	var match_ids []int
	for _, v := range ret.LivePlan {
		match_ids = append(match_ids, int(v.MatchId))
	}

	var matches []*models_sports.MatchTempSchedule
	err = global.Sport().Model(&models_sports.MatchTempSchedule{}).Where("match_id in (?)", match_ids).Scan(&matches).Error
	if err != nil {
		return &pb.AnchorLivePlanResp{}, err
	}

	for idx, v := range ret.LivePlan {
		for _, mv := range matches {
			if v.MatchId == int32(mv.MatchId) {
				ret.LivePlan[idx].MatchEvent = mv.Comp
				ret.LivePlan[idx].MatchHomeTeam = mv.Home
				ret.LivePlan[idx].MatchAwayTeam = mv.Away
			}
		}
	}

	return ret, nil
}

func (*Server) LiveAnchorPlanCancel(ctx context.Context, req *pb.AnchorLivePlanCancelReq) (*pb.AnchorLivePlan, error) {
	ret := &pb.AnchorLivePlan{}
	err := global.Live().Model(&models_main.AnchorLivePlan{}).Where("id=?", req.Id).Update("status", 3).Scan(&ret).Error
	if err != nil {
		return &pb.AnchorLivePlan{}, err
	}
	if ret.AnchorId != req.Anchorid {
		return nil, errors.New("主播数据异常")
	}
	return ret, nil
}

func (*Server) LiveByAnchorPlan(ctx context.Context, req *pb.ByAnchorLivePlanReq) (*pb.ByAnchorLivePlanResp, error) {
	ret := &pb.ByAnchorLivePlanResp{}
	err := global.Live().Model(&models_main.AnchorLivePlan{}).Where("anchor_id=? and status=0", req.Id).Count(&ret.Total).Scan(&ret.LivePlan).Error
	if err != nil {
		return &pb.ByAnchorLivePlanResp{}, err
	}

	var match_ids []int
	for _, v := range ret.LivePlan {
		match_ids = append(match_ids, int(v.MatchId))
	}

	var matches []*models_sports.MatchTempSchedule
	err = global.Sport().Model(&models_sports.MatchTempSchedule{}).Where("match_id in (?)", match_ids).Scan(&matches).Error
	if err != nil {
		return &pb.ByAnchorLivePlanResp{}, err
	}

	for idx, v := range ret.LivePlan {
		for _, mv := range matches {
			if v.MatchId == int32(mv.MatchId) {
				ret.LivePlan[idx].MatchEvent = mv.Comp
				ret.LivePlan[idx].MatchHomeTeam = mv.Home
				ret.LivePlan[idx].MatchAwayTeam = mv.Away
			}
		}
	}
	return ret, nil
}

func (*Server) PlanStartLive(ctx context.Context, req *pb.PlanStartLiveReq) (*pb.PlanStartLiveResp, error) {
	// 取直播计划
	plan := &models_main.AnchorLivePlan{}
	err := global.Live().Model(&models_main.AnchorLivePlan{}).Where("id=?", req.Id).First(&plan).Error
	if err == gorm.ErrRecordNotFound {
		return nil, errors.New("数据异常")
	}

	if plan.AnchorID != req.Uid {
		return nil, errors.New("主播计划与记录ID不匹配")
	}

	// 赛事信息
	match := &models_sports.MatchTempSchedule{}
	err = global.Sport().Model(&models_sports.MatchTempSchedule{}).Where("match_id=?", plan.MatchID).First(&match).Error
	if err != nil {
		return nil, err
	}

	// 主播信息
	user, err := mysql.GetUserParam(map[string]interface{}{"id": plan.AnchorID})
	if err != nil {
		return nil, err
	}

	base := api.Controller{}
	var liveParams api_models.StartLiveReq
	liveParams.Title = plan.Title
	liveParams.Ticket = plan.Ticket
	liveParams.MatchId = int(match.MatchId)
	liveParams.Category = plan.CategoryID
	liveParams.Cateid = plan.ChildCategoryID
	liveParams.Thumb = plan.Thumb

	_, err = base.Service.StartLive(&liveParams, user, &api_models.LivePlugins{
		LiveStatus: int(cache.StartLive),
	})

	if err != nil {
		return nil, err
	}

	// 更新开播计划状态
	global.Live().Model(&models_main.AnchorLivePlan{}).Where("id=?", req.Id).Update("status", _const.LIVE_PLAN_STATUS_LIVING)

	return &pb.PlanStartLiveResp{
		Status: 1,
	}, nil
}
